﻿using SuperX.Common.Log;
using SuperSocket.SocketBase.Command;
using SuperSocket.SocketBase.Protocol;
using System;
using System.IO;

namespace SuperX.SuperSocket.Socket.Transfer.Server.UpLoad.Command
{
    public class DoCheckExist : CommandBase<TransferSession, BinaryRequestInfo>
    {
        public override string Name => "DoCheckExist";

        public override void ExecuteCommand(TransferSession session, BinaryRequestInfo requestInfo)
        {
            ConsoleLogHelper.Debug(Name);
            try
            {
                FileInfo ClientConfigInfo = SerializeHelp.Deserialize<FileInfo>(requestInfo.Body);
                string saveName = Path.GetFullPath(ClientConfigInfo.FileName);
                var configInfo = new FileInfo();
                configInfo.PacketSize = ClientConfigInfo.PacketSize;
                configInfo.ProjectId = Guid.NewGuid().ToString();
                configInfo.SaveName = ClientConfigInfo.SaveName;
                configInfo.TransferedLength = 0;
                configInfo.TransferPos = 0;
                configInfo.FileName = ClientConfigInfo.FileName;
                configInfo.DownloadAutoDelFile = ClientConfigInfo.DownloadAutoDelFile;
                if (!File.Exists(ClientConfigInfo.FileName))
                {
                    configInfo.FileSize = -1;
                    configInfo.TransferLength = 0;
                }
                else
                {
                    session.FileTransferEngine.m_fileStream = new FileStream(ClientConfigInfo.FileName, FileMode.Open, FileAccess.Read);
                    configInfo.FileSize = session.FileTransferEngine.m_fileStream.Length;
                    configInfo.TransferLength = session.FileTransferEngine.m_fileStream.Length;
                    session.FileTransferEngine.OnStartTransfer(configInfo);
                    //SerializeHelp.SerializeToFile<FileInfo>(configInfo, configName);
                }
                byte[] data = SerializeHelp.Serialize(configInfo);
                session.FileTransferEngine.SendData(UpLoadOP.DoCheckExist, data, 0, data.Length);
            }
            catch (Exception ex)
            {
                Logger.Error(ex.Message);
            }
        }
    }
}